const db = require('../../db/index')
const { isUrl } = require('../../utils/util')
const APP_CONFIG = require('../../utils/config') 
/**
 * @name addCate
 * @description 添加分类
 * 需要上一级分类id和分类名必填写
 * 别名 没有传递别名默认则是当前分类名 分类描述 没有描述 也默认是当前的分类名称
 * 刚创建的分类默认下面文章为空
 * */
exports.addCate = (req,res) => {
    let {cateName,cateParentId,cateAlias,cateDesc,cateArticles} = req.body
    if(!cateName) return res.send({code:400,message:'分类名为必填项目'})
    if(!cateParentId) return  res.send({code:400,message:'请选择分类的父级分类'})
    cateAlias = cateAlias ? cateAlias : cateName
    cateDesc = cateDesc ? cateDesc : cateName
    cateArticles = ''
    let insertSql = "insert into cates(cateName,cateParentId,cateAlias,cateDesc,cateArticles) values(?,?,?,?,?)"
    console.log('添加分类参数',cateName,cateParentId,cateAlias,cateDesc,cateArticles)
    db.query(insertSql,[cateName,cateParentId,cateAlias,cateDesc,cateArticles],(err,result)=>{
        if(err){
            if(err.sqlState == '23000') return res.send({code:400,message:'当前已经存在该分类'})
            return res.send({code:400,message:err.sqlMessage})
        }
        res.send({code : 200 ,message:'添加分类成功',cate:{id:result.insertId,cateName,cateParentId,cateAlias,cateDesc}})
    })
}

/**
 * @description 删除分类
 * 根据id删除分类 但是如果当前分类下面有文章则不允许删除
 * */

exports.removeCate = (req,res) => {
    let {cateId} = req.body
    cateId = cateId.split(',')
    // 删除之前先去查询当前数据分类下面是否包含了文章
    let findSql =  "select cateArticles from cates where cateId in (?)"
    db.query(findSql,[cateId],(error,response) => {
        if(error) return res.send({code:400,message:error.sqlMessage})
        console.log('当前分类信息',response)
        if(response.length == 0) return  res.send({code:400,message:'删除失败未找到该分类'})
        let done = true
        // 判断里面是否包含有含有文章的分类
        response.forEach(item => {
            if(item.cateArticles != '') {
                done = false
            }
        })
        done == true ? deleteCate(cateId,req,res) : res.send({code:400,message:'分类下面有文章，不允许删除'})
    })
}


function deleteCate(cateId,req,res){
    let deleteSql = "delete from cates where cateId in (?)"
    db.query(deleteSql,[cateId],(err,result) => {
        if(err) return res.send({code:400,message:err.sqlMessage})
        if(result.affectedRows >= 1) {
            res.send({code:200,message:'删除分类成功'})
            return
        }
    })
}

/**
 * 更新当前分类的字段
 * @description 更新当前分类的信息
 * 修改当前分类的名称 介绍 和 别名
 * */

exports.updateCate = (req,res) => {
    let {cateId} = req.params
    let {cateName,cateAlias,cateDesc} = req.body
    // 先进行查询当前数据在数据库里面的表现
    let findSql = "select cateName,cateAlias,cateDesc from cates where cateId = ?"
    db.query(findSql,[cateId],(err,result) => {
        if(err) return res.send({code:400,message:err.sqlMessage})
        if(result.length == 0) return res.send({code:400,message:'未找到该分类'})
        let {cateName:oldCateName,cateAlias:oldCateAlias,cateDesc:oldCateDesc} = result[0] // 将数据库里面的字段进行声明
        cateName = cateName ? cateName : oldCateName
        cateAlias = cateAlias ? cateAlias : oldCateAlias
        cateDesc = cateDesc ? cateDesc : oldCateDesc
        // 开始更新
        let updateSql = "update cates set cateName = ?,cateAlias = ?,cateDesc = ? where cateId = ?"
        db.query(updateSql,[cateName,cateAlias,cateDesc,cateId],(error,response) => {
            if(error) {
                console.log('error',error)
                res.send({code:400,message:error.sqlMessage})
                return
            }
            console.log('更新分类',response)
            let updateCateInfo = {cateId,cateName,cateAlias,cateDesc}
            res.send({code:200,message:'更新分类成功',updateCateInfo})
        })
    })
}

/**
 *@description 获取该分类下面所有文章
 * 查询分类文章sql
 * SELECT * from `articles` WHERE FIND_IN_SET(articleId,(SELECT cateArticles from `cates` WHERE cateId = 11))
 * 查询分类文章数量sql
 * SELECT COUNT(s.articleId) FROM (SELECT * from `articles` WHERE FIND_IN_SET(articleId,(SELECT cateArticles from `cates` WHERE cateId = 11))) as s
 * */
exports.getCateArticle = (req,res) => {
    let {page,pageSize,cateId} = req.query // 提供查询第几页和当前每页数量 2 ， 10
    if(cateId=='' || cateId == undefined || cateId == 0) cateId = null
    page = page ? page*1 : 1
    pageSize = pageSize ? pageSize * 1 : 10
    let startIndex = (page - 1) * pageSize
    let endIndex = pageSize
    let count = 0
    let selectCountSql = "SELECT COUNT(s.articleId) FROM (SELECT * from articles WHERE FIND_IN_SET(articleId,(SELECT cateArticles from cates WHERE cateId = ?))) as s"
    let noCateIdCountSql = "SELECT COUNT(articleId) FROM articles"
    // SELECT * from ((SELECT * from articles WHERE FIND_IN_SET(articleId,(SELECT cateArticles from cates WHERE cateId = 1))) as s) INNER JOIN `users` ON s.publicUserId = users.userId order by articleId DESC
    let selectSql = cateId ? `
       SELECT 
        a.articleId,
        a.articleTitle,
        a.articleContent,
        a.publicTime,
        a.publicUserId,
        a.likeCount,
        a.repliesCount,
        a.viewsCount,
        GROUP_CONCAT(DISTINCT c.cateId) AS cateIds,
        GROUP_CONCAT(DISTINCT c.cateName) AS cateNames,
        GROUP_CONCAT(DISTINCT t.tagId) AS tagIds,
        GROUP_CONCAT(DISTINCT t.tagName) AS tagNames,
        a.articleCover,
        a.articleDesc,
        u.userId,
        u.userAvatar,
        u.userIp,
        u.userName,
        u.userParty
    FROM (
        SELECT *
        FROM articles
        WHERE FIND_IN_SET(articleId, (SELECT cateArticles FROM cates WHERE cateId = ${cateId}))
    ) AS a
    INNER JOIN users AS u ON a.publicUserId = u.userId
    INNER JOIN cates AS c ON FIND_IN_SET(c.cateId, a.cates)
    LEFT JOIN tags AS t ON FIND_IN_SET(t.tagId, a.tags)
    GROUP BY a.articleId order by a.publicTime DESC limit ${startIndex},${endIndex}` :
        `
       SELECT 
        a.articleId,
        a.articleTitle,
        a.articleContent,
        a.publicTime,
        a.publicUserId,
        a.likeCount,
        a.repliesCount,
        a.viewsCount,
        GROUP_CONCAT(DISTINCT c.cateId) AS cateIds,
        GROUP_CONCAT(DISTINCT c.cateName) AS cateNames,
        GROUP_CONCAT(DISTINCT t.tagId) AS tagIds,
        GROUP_CONCAT(DISTINCT t.tagName) AS tagNames,
        a.articleCover,
        a.articleDesc,
        u.userId,
        u.userAvatar,
        u.userIp,
        u.userName,
        u.userParty
    FROM (
        SELECT *
        FROM articles
    ) AS a
    INNER JOIN users AS u ON a.publicUserId = u.userId
    INNER JOIN cates AS c ON FIND_IN_SET(c.cateId, a.cates)
    LEFT JOIN tags AS t ON FIND_IN_SET(t.tagId, a.tags)
    GROUP BY a.articleId order by a.publicTime DESC limit ${startIndex},${endIndex}`
    db.query(cateId ? selectCountSql : noCateIdCountSql,[cateId],(err,result) =>{
        if(err) return  res.send({code:400,message:err.sqlMessage})
        count = cateId ? result[0]['COUNT(s.articleId)'] : result[0]['COUNT(articleId)']
        db.query(selectSql,(err,result) => {
            // console.log('res',result)
            if(err) return  res.send({code:400,message:err.sqlMessage})
            // 将获取到的分类的名称进行拆分成数组形式
            result.forEach(item => {
                let {tagIds,tagNames,cateIds,cateNames} = item
                item.tagIds = tagIds ? tagIds.split(',') : []
                item.tagNames = tagNames ? tagNames.split(',') : []
                item.cateIds = cateIds ? cateIds.split(',') : []
                item.cateNames = cateNames ? cateNames.split(',') : []
                item.articleCover = isUrl(item.articleCover) ? item.articleCover : APP_CONFIG.imagePrefixe + item.articleCover
                let tags = []
                for(let i = 0 ; i < item.tagIds.length;i++){
                    let obj = {tagId:'',tagName:''}
                    obj.tagId = item.tagIds[i]
                    obj.tagName = item.tagNames[i]
                    tags.push(obj)
                }
                let cates = []
                for(let i = 0 ; i < item.cateIds.length ;i++){
                    let obj = {cateId:'',cateName:''}
                    obj.cateId = item.cateIds[i]
                    obj.cateName = item.cateNames[i]
                    cates.push(obj)
                }
                item.tags = tags
                item.cates = cates
            })
            res.send({code:200,message:'查询分类成功',articles:result,count})
        })
    })
}


exports.getCateList = async (req,res) => {
    try {
        let done = await getCateListHandler(req,res)
        if(done.length > 0) {
            res.send({code:200,message:"获取分类数据成功",cates:done})
        }
    }catch (e) {
        res.send({code:400,message:e.message})
    }
}

let getCateListHandler = (req) => {
    const findSql = "select * from cates"
    return new Promise((resolve,reject) => {
        try {
            db.query(findSql,(err,result) => {
                if(err) {
                    return reject(err.sqlMessage)
                }
                return resolve(result)
            })
        }catch (e) {
            return reject(e)
        }
    })
}

